package com.study.springBoot.controller;

import com.study.springBoot.domain.User;
import com.study.springBoot.service.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class HomeController {
    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
        Map data = new HashMap();
        data.put("title", "首页");
        data.put("desc", "这是一个学习spring boot的项目");

        ModelAndView mv = new ModelAndView("home");
        mv.addObject("message", "welcome to spring boot");
        mv.addObject("data", data);

        return mv;
    }

//    @RequestMapping("/login")
//    @ResponseBody
//    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        if (request.getMethod() == "POST") {
//            User user = userRepository.findUserByName((String) request.getAttribute("name"));
//            if (user != null) {
//                response.sendRedirect("/");
//            }
//        }
//        ModelAndView mv = new ModelAndView("login");
//        return mv;
//    }

    @RequestMapping("/register")
    @ResponseBody
    public ModelAndView register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ModelAndView mv = new ModelAndView("register");
        if (request.getMethod().equals("POST")) {
            Date date = new Date();
            Long nowTime = (date.getTime()) / 1000;

            User user = new User();
            user.setName((String) request.getParameter("name"));
            user.setNickname((String) request.getParameter("nickname"));
            user.setPassword((String) request.getParameter("password"));
            user.setInsertTime(nowTime);
            this.userRepository.save(user);

            mv.setViewName("success");
            mv.addObject("message", "注册成功");
            mv.addObject("url", "/login");
        }
        return mv;
    }
}